package edu.uwosh.cs342.project4;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.location.Address;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class SetLocation extends Activity{
	
	private TextView location;
	private List<Address> addresses;
	private ArrayList<String> results;
	private ListView resultList;
	private String previousSearch = "";
	private ResultsThread resultThread;
	private AddressHelper addressHelper;
	
	//This handler updates the UI after new results are found
	final Handler myHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			resultList.setAdapter(new ArrayAdapter(resultList.getContext(), 
					R.layout.result_list_item, results));
		}
		};

	
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dialog);
		
		addressHelper = new AddressHelper();
		location = (TextView)findViewById(R.id.textViewLocation);
		results = new ArrayList<String>();
		
		resultList = (ListView)findViewById(R.id.resultList);
		resultList.setTextFilterEnabled(true);
		resultList.setOnItemClickListener(new OnItemClickListener(){

			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				Intent myIntent = new Intent();
				myIntent.putExtra("location", results.get(position));
				myIntent.putExtra("address", addresses.get(position));
				setResult(Project4Activity.RESULT_LOCATION, myIntent);
				finish();
			}});
		
		resultThread = new ResultsThread();
		resultThread.start();
		
		Button cancel = (Button)findViewById(R.id.buttonCancel);
		cancel.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				resultThread.stop();
				finish();
			}
		});//end cancel button listener
	}//end onCreate
	
	private class ResultsThread extends Thread{
		@Override
		public void run(){
			while (true){
				try{
					String search = location.getText().toString();
					if (!search.isEmpty() && search.compareTo(previousSearch) != 0){
						addresses = addressHelper.getAddressesFromName(SetLocation.this, location.getText().toString());
						results.clear();
						for (int i = 0; i < addresses.size(); i++){
							results.add(addressHelper.addressLineBuilder(addresses.get(i)));
						}
						myHandler.sendEmptyMessage(0);
						previousSearch = search;
					}
					sleep(1000);
				}
				catch(InterruptedException e){
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}//end while loop
		}//end run
	}//end private class ResultsThread
}//end class
